package com.fy.fyspace.ex.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.reactive.function.client.WebClientRequestException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * SSE异常处理类
 * 专门处理Server-Sent Events相关的异常
 */
@Slf4j
@ControllerAdvice
public class SseExceptionHandler {

    /**
     * 处理WebClient请求异常
     * 主要用于处理SSE流式响应中的WebClient异常
     */
    @ExceptionHandler(WebClientRequestException.class)
    public void handleWebClientRequestException(WebClientRequestException ex, 
                                                HttpServletRequest request,
                                                HttpServletResponse response) throws IOException {
        log.error("WebClient请求异常: {}", ex.getMessage());
        
        // 检查是否是SSE请求
        if (request.getRequestURI().contains("/chatStream")) {
            response.setContentType(MediaType.TEXT_EVENT_STREAM_VALUE);
            response.setCharacterEncoding("UTF-8");
            
            // 发送SSE格式的错误消息
            response.getWriter().write("event: error\n");
            response.getWriter().write("data: API服务连接失败，请检查网络或服务配置\n\n");
            response.getWriter().flush();
        }
    }
    
    /**
     * 处理SseEmitter相关异常
     */
    @ExceptionHandler(IllegalStateException.class)
    public void handleIllegalStateException(IllegalStateException ex,
                                           HttpServletRequest request,
                                           HttpServletResponse response) throws IOException {
        if (ex.getMessage() != null && ex.getMessage().contains("SseEmitter")) {
            log.error("SSE连接异常: {}", ex.getMessage());
            
            if (request.getRequestURI().contains("/chatStream")) {
                response.setContentType(MediaType.TEXT_EVENT_STREAM_VALUE);
                response.setCharacterEncoding("UTF-8");
                
                response.getWriter().write("event: error\n");
                response.getWriter().write("data: SSE连接已关闭或超时\n\n");
                response.getWriter().flush();
            }
        }
    }
} 